package com.fyf.game.net.server;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.util.LinkedList;
import java.util.List;
import com.fyf.game.net.DataAnalyzer;
import com.fyf.game.net.GameProtocol;
import com.fyf.game.net.SelectManager;

/**
 * @author fanyifeng
 */
public class DataManager
{
	private DataAnalyzer		ana;
	private List<ByteBuffer>	writeDatas;
	private SelectionKey		key;
	private SelectManager		selMgr;

	public DataManager(SelectManager selMgr) {
		this.writeDatas = new LinkedList<ByteBuffer>();
		this.selMgr = selMgr;
	}

	public void setAnalyzerAndKey(DataAnalyzer ana, SelectionKey key) {
		this.ana = ana;
		this.key = key;
	}

	public DataAnalyzer analyzer() {
		return ana;
	}

	public void put(String msg) {
		ByteBuffer bf = GameProtocol.wrap(msg);
		synchronized(writeDatas) {
			writeDatas.add(bf);
			key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
		}
		selMgr.wakeup();
	}

	public ByteBuffer getWriteData() {
		synchronized(writeDatas) {
			if (writeDatas.size() == 0) {
				return null;
			}
			return writeDatas.get(0);
		}
	}

	/**
	 * @param updateKey2Read
	 */
	public void removeFirstWriteData(boolean updateKey2Read) {
		synchronized(writeDatas) {
			writeDatas.remove(0);
			if (updateKey2Read && writeDatas.size() == 0) {
				key.interestOps(SelectionKey.OP_READ);
			}
		}
	}

	String senderID() {
		return ana.senderID();
	}
	
	public SelectionKey getKey(){
		return this.key;
	}
}
